package com.mvvm.store.ui.stockup;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;

import androidx.viewpager.widget.ViewPager;

import com.leo.utilspro.utils.DataUtils;
import com.leo.utilspro.utils.ToastUtils;
import com.mvvm.store.R;
import com.mvvm.store.base.BaseActivity;
import com.mvvm.store.base.BaseFragment;
import com.mvvm.store.base.NormalViewModel;
import com.mvvm.store.bean.basebean.DeliveryInfoBean;
import com.mvvm.store.bean.basebean.ScanStockBean;
import com.mvvm.store.bean.basebean.StockUpGetListResultBean;
import com.mvvm.store.bean.basebean.StockUpInfoBean;
import com.mvvm.store.bean.basebean.StockUpResultBean;
import com.mvvm.store.customview.CustomProgress;
import com.mvvm.store.databinding.FragmentDeliveryInfoBinding;
import com.mvvm.store.databinding.FragmentStockInfoBinding;
import com.mvvm.store.roombatabase.ScanStockDao;
import com.mvvm.store.roombatabase.ScanStockDatabase;
import com.mvvm.store.roombatabase.StockUpInfoDao;
import com.mvvm.store.roombatabase.StoreHouseDatabase;
import com.mvvm.store.ui.delivery.adapter.DeliveryInfoAdapter;
import com.mvvm.store.ui.stockup.adapter.StockInfoAdapter;

import java.util.ArrayList;
import java.util.List;

import static android.content.Context.MODE_PRIVATE;


/**
 * Created by leo     MVVM
 * @author  zhouchangyi
 * on 2021/06/15.   备货物料信息界面
 */
public class StockUpInfoFragment extends BaseFragment<StockUpViewModel, FragmentStockInfoBinding>{

    int index;
    private StockInfoAdapter infoAdapter;
    private int curPage = 0;
    private ArrayList<StockUpInfoBean> stockUpInfoBeansListToLoad = new ArrayList<>();
    private CustomProgress dialog;
    private  String orderId;
    private StockUpInfoDao stockUpInfoDao;
    private  List<StockUpInfoBean> stockUpInfoBeans;
    private ScanStockDao scanStockDao;


    public static StockUpInfoFragment newInstance(final String name, ViewPager viewPager) {
        StockUpInfoFragment mFragment = new StockUpInfoFragment();
        Bundle bundle = new Bundle();
        bundle.putString("name", name);
        mFragment.setArguments(bundle);
        return mFragment;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_stock_info;
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
        handler.postDelayed(runnables, TIME); // 在初始化方法里.
        stockUpInfoDao=StoreHouseDatabase.getInstance(getActivity()).stockUpDao();
        scanStockDao= ScanStockDatabase.getInstance(getActivity()).scanStockDao();
        //Sp获取点击备货列表数据的订单号的值
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("stockInfo", MODE_PRIVATE);
        orderId=sharedPreferences.getString("orderId","");
        System.out.println("orderId---------备货-----------"+orderId);
        if(dialog==null) {
            dialog = CustomProgress.show(getActivity(), "", true, null);
        }
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(500);//休眠3秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                /**
                 * 要执行的操作
                 */
                dialog.dismiss();
            }
        }.start();
        binding.includeEmpty.setTextEmpty("瞅啥，没有你的收藏~");
        binding.includeEmpty.setImageEmpty(R.mipmap.no_data);

        infoAdapter=new StockInfoAdapter();
        infoAdapter.setDataList(stockUpInfoBeansListToLoad);
        binding.recyclerView.setAdapter(infoAdapter);

    /*    //获取本地备货的数据
        stockUpInfoBeans= stockUpInfoDao.getStockUpInfoByOrderNumber("DEMO001");
        if(stockUpInfoBeans.size()>0) {
            binding.includeEmpty.relativeNull.setVisibility(View.GONE);
            for (int i = 0; i < stockUpInfoBeans.size(); i++) {
                stockUpInfoBeansListToLoad.add(stockUpInfoBeans.get(i));
            }
        }else {
            binding.includeEmpty.relativeNull.setVisibility(View.VISIBLE);
        }*/
        //根据订单号请求接口获取数据 //---------------------------------
        mViewModel.getStockIdList(orderId).observe(this,resourse->resourse.handler(new OnCallback<List<StockUpGetListResultBean>>() {
            @Override
            public void onSuccess(List<StockUpGetListResultBean> data) {
                System.out.println("接口获取数据json"+data.toString());
                if(data!=null) {
                    binding.includeEmpty.relativeNull.setVisibility(View.GONE);
                    if(data.size()>0) {
                        //将获取到的接口数据设置到对应的控件中  备货
                        binding.tvStockOrderNumber.setText(orderId);
                        binding.tvIntoSupplierName.setText(data.get(0).getSupplierName() + "");
                        //查看本地数据库是否有数据 备货
                            for (int i=0;i<data.size();i++){
                                //根据订单号和对应的零件号查询本地数据库是否有这条数据 有不管没有就添加到本地数据库中
                              List<StockUpInfoBean> stockUpInfoBeanList=  stockUpInfoDao.getStockUpInfoByOddNumber(orderId,data.get(i).getPartNumber());
                                if(stockUpInfoBeanList.size()>0){
                                    System.out.println("查询的该订单号对应的零件号本地数据存在了");
                                }else {
                                    System.out.println("本地数据库没有数据进行添加到本地数据");
                                    //本地数据库不存在进行插入到本地数据库中
                                    StockUpInfoBean stockUpInfoBean=new StockUpInfoBean();
                                    stockUpInfoBean.setOrderNumber(orderId);
                                    stockUpInfoBean.setOddNumber(data.get(i).getPartNumber());
                                    stockUpInfoBean.setSnpNumber(data.get(i).getSnpCount());
                                    stockUpInfoBean.setSumNumber(data.get(i).getStockTotal());
                                    stockUpInfoBean.setPackNumber(data.get(i).getBoxCount());
                                    stockUpInfoBean.setOddName(data.get(i).getPartName());
                                    stockUpInfoBean.setRealToNumber(0);
                                    stockUpInfoBean.setRealToPack(0);
                                    stockUpInfoBean.setSupplierCode(data.get(i).getSupplierCode());
                                    stockUpInfoBean.setSupplierName(data.get(i).getSupplierName());
                                    stockUpInfoDao.insertAll(stockUpInfoBean);

                                }
                                //-------------------------------------保存标签-------------------------------------
                                if(data.get(i).getInventorys()==null){
                                    ToastUtils.showToast("备货订单中未能找到对应的标签信息");
                                }else {
                                    for (int j = 0; j < data.get(i).getInventorys().size(); j++) {
                                        List<ScanStockBean> scanStockBeans = scanStockDao.getScanStockBeanByLableNumber(data.get(i).getInventorys().get(j).getTagCode());
                                        if (scanStockBeans.size() > 0) {
                                            System.out.println("标签读取接口表有对应的标签了--------------");
                                        } else {
                                            ScanStockBean scanStockBean = new ScanStockBean();
                                            scanStockBean.setLableNumber(data.get(i).getInventorys().get(j).getTagCode());
                                            scanStockBean.setOddNumber(data.get(i).getPartNumber());
                                            System.out.println("添加的人时候---------------------------------" + scanStockBean.toString());
                                            scanStockDao.insertAll(scanStockBean);
                                        }
                                    }
                                }
                            }
                            //添加完进行查询刷新适配器
                            stockUpInfoBeans= stockUpInfoDao.getStockUpInfoByOrderNumber(orderId);
                            stockUpInfoBeansListToLoad.clear();
                            if(stockUpInfoBeans.size()>0) {
                                for (int i = 0; i < stockUpInfoBeans.size(); i++) {
                                    stockUpInfoBeansListToLoad.add(stockUpInfoBeans.get(i));
                                }
                            }
                            infoAdapter.notifyDataSetChanged();


                    }else {
                        binding.tvStockOrderNumber.setText("无数据");
                        binding.tvIntoSupplierName.setText("无数据");
                    }
                }else {
                    binding.includeEmpty.relativeNull.setVisibility(View.VISIBLE);
                }


            }
        }));
    }
    @Override
    protected void setListener() {
        binding.setOnClickListener(this::onClick);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_supplier:

                break;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden){
            System.out.println("MaterialInfoFragment----hidden");
        }else {
            System.out.println("MaterialInfoFragment------no----hidden");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(handler!=null) {
            handler.removeCallbacks(runnables);
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            //TODO 刷新数据方法在这里调用
            System.out.println("MaterialInfoFragmentsetUserVisibleHint刷新数据");
            if(infoAdapter!=null && !TextUtils.isEmpty(orderId)) {
                stockUpInfoBeans= stockUpInfoDao.getStockUpInfoByOrderNumber(orderId);
                stockUpInfoBeansListToLoad.clear();
                for (int i=0;i<stockUpInfoBeans.size();i++){
                    stockUpInfoBeansListToLoad.add(stockUpInfoBeans.get(i));
                }
                infoAdapter.notifyDataSetChanged();

              /*  StockUpInfoBean materialInfoBean5=new StockUpInfoBean();
                materialInfoBean5.setOddNumber("T122YE3452323453534537");
                materialInfoBean5.setLableNumber("44232");
                materialInfoBean5.setPackNumber("523424");
                materialInfoBean5.setSnpNumber("32244");
                materialInfoBean5.setSumNumber("675422");
                stockUpInfoBeans.add(materialInfoBean5);
                infoAdapter.notifyDataSetChanged();*/
            }
        }
    }
    private int TIME = 1000;  //每隔1s执行一次.
    Handler handler = new Handler();

    Runnable runnables=new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(this, TIME);
            //刷新数据
            // materialInfoBeans.clear();
            // getMaterInforTointent();
            System.out.println("出库扫码监听数据,刷新列表");
            if(infoAdapter!=null && !TextUtils.isEmpty(orderId)) {
                stockUpInfoBeans = stockUpInfoDao.getStockUpInfoByOrderNumber(orderId);
                stockUpInfoBeansListToLoad.clear();
                for (int i = 0; i < stockUpInfoBeans.size(); i++) {
                    stockUpInfoBeansListToLoad.add(stockUpInfoBeans.get(i));
                }
                infoAdapter.notifyDataSetChanged();

            }
            }
    };
}
